﻿/*jslint */
/*global openDatabase: true, $: true */
"use strict";

//

var Page_ContactDetails = (function () {

    var contactID;

    function errorHandler(transaction, error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    function errorHandlerSimple(error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    function DateDiff(date1, date2) {
        console.log("entering: DateDiff");
        console.log("date1: " + date1);
        console.log("date2: " + date2);

        return date1.getTime() - date2.getTime();
    }

    /*calculate_LastContactedInfo*/
    function calculate_LastContactedInfo(oTimeAgo) {
        console.log("entering: calculate_LastContactedInfo");

        var secondsInAYear = 31556000;      //seconds in a year
        var secondsInAMonth = 2630000;      //seconds in a month
        var secondsInAWeek = 604800;        //seconds in a week
        var secondsInADay = 86400;           //seconds in a day
        var secondsInAnHour = 3600;           //seconds in an hour
        var secondsInAMinute = 60;           //seconds in a minutes

        console.log(oTimeAgo.lastContactedDate);

        //Find the Difference in Seconds
        var d = new Date();
        var d2 = Date.parse(oTimeAgo.lastContactedDate);                     //converts it to milliseconds - as if get..time

        var _contactedSinceInSeconds = (d.getTime() - d2) / 1000;   //in milliseconds

        var result = '';
        if (_contactedSinceInSeconds >= secondsInAYear) {
            //Do we have enough for years?
            result += 'More Than ' + parseInt((_contactedSinceInSeconds / secondsInAYear), 10) + ' Year(s) Ago';
            oTimeAgo.flagColor = "status_off";
        }
        else if (_contactedSinceInSeconds >= secondsInAMonth) {
            //how many months exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAMonth), 10) + ' Month(s) Ago';
            oTimeAgo.flagColor = "status_off";
        }
        else if (_contactedSinceInSeconds >= secondsInAWeek) {
            //how many weeks exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAWeek), 10) + ' Week(s) Ago';
            oTimeAgo.flagColor = "status_away";
        }
        else if (_contactedSinceInSeconds > secondsInADay) {
            //how many days exactly
            var howManyDays = parseInt((_contactedSinceInSeconds / secondsInADay), 10);
            result += howManyDays + ' Day(s) Ago';

            if (howManyDays > 3) {
                oTimeAgo.flagColor = "status_available"; //green
            }
            else {
                //TODO:make it a setting
                //more than 3 days
                oTimeAgo.flagColor = "status_away";      //yellow
            }
        }
        else if (_contactedSinceInSeconds > secondsInAnHour) {
            //how many hours exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAnHour), 10) + ' Hour(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }
        else if (_contactedSinceInSeconds > secondsInAMinute) {
            //how many minutes exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAMinute), 10) + ' Minute(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }
        else if (_contactedSinceInSeconds > 0.05) {
            //how many minutes exactly
            result += parseInt(_contactedSinceInSeconds, 10) + ' Second(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }

        console.log('_contactedSinceInSeconds in sec: ' + _contactedSinceInSeconds)
        console.log('the result is: ' + result);
        //return the last contacted text
        oTimeAgo.lastContactedInfo = result;
        return result;
    }

    /*calculate_TimeSinceLastContacted*/
    function calculate_TimeSinceLastContacted(singleContact, oTimeAgo) {

        //get the lastcontacted from the contact infor
        var _lastContactedDate;
        var _dateCreated = singleContact.DateCreated;

        //Set the last Contacted
        _lastContactedDate = _dateCreated;      //we should
        if (singleContact.DateLastContacted)
            _lastContactedDate = singleContact.DateLastContacted;

        //Get the last Contacted Info Text
        oTimeAgo.lastContactedDate = _lastContactedDate
        var _lastContactedInfo = calculate_LastContactedInfo(oTimeAgo);

        //oTimeAgo.lastContactedInfo = _lastContactedInfo;
        //oTimeAgo.flagColor = flagColor;

        return oTimeAgo;
    }

    /*populateDisplay_ContactInfo*/
    function populateDisplay_ContactInfo(oSingleContact)
    {
        console.log("entering: populateDisplay_ContactInfo");
        /********************************/
        //some weird object
        /********************************/
        var oDisplay = new Object();
        oDisplay.lastContactedDate = '';
        oDisplay.lastContactedInfo = '';
        oDisplay.flagColor = '';
        /********************************/

        //handle the picture
        oDisplay.picturePath = oSingleContact.picturePath;
        if (!oSingleContact.picturePath) {
            //avatar picture
            oDisplay.picturePath = 'images/live/avatar_noPic.png';
        }

        $("#contactDetails_Pic").attr("src", oDisplay.picturePath);

        //TODO:Move this function into a utility
        calculate_TimeSinceLastContacted(oSingleContact, oDisplay)

        //title
        $('#contactDetails_HeaderName').html(oSingleContact.displayName);
        $('#contactDetails_name').html(oSingleContact.displayName);
        $('#contactDetails_lastcontated').html(oDisplay.lastContactedInfo);
    }

    function buildIconLink(functionality,value)
    {   
        var result;
        switch (functionality){

            case 'call':
                result = '<a href="tel:' + value + '" title="call ' + value + '" id="contactDetails_telephone" class="tablectrl_medium bGreen" style="margin-left: 10px;"><span class="iconb" data-icon="&#xe01d;"></span></a>'
                break;
            case 'text_message':
                result = '<a href="sms:' + value + '" title="send text to ' + value + '" id="contactDetails_textmessage" class="tablectrl_medium bGold" style="margin-left: 10px;"><span class="iconb" data-icon="&#xe01e;"></span></a>'
                break;
            case 'email':
                result = '<a href="mailto:' + value + '" title="email ' + value + '" id="contactDetails_email" class="tablectrl_medium bRed" style="margin-left: 10px;"><span class="iconb" data-icon="&#xe198;"></span></a>';
                break;
            case 'facebook':
                result = '<a href="facebook:' + value + '" title="send facebook message to  ' + value + '" id="contactDetails_facebook" class="tablectrl_medium bLightBlue" style="margin-left: 10px;"><span class="iconb" data-icon="&#xe0ea;"></span></a>';
                break;
            case 'twitter':
                result = '<a href="twitter:' + value + '" title="send twitter message to ' + value + '" id="contactDetails_twitter" class="tablectrl_medium bSea" style="margin-left: 10px;"><span class="iconb" data-icon="&#xe0ec;"></span></a>'
                break;
        }

        return result;
    }

    /*********************************************************/
    /*populateDisplay_LastContacted */
    /*********************************************************/
    function populateDisplay_LastContacted(lastContactedDate) {
        console.log("entering: populateDisplay_LastContacted");

        //just update the last contacted
        var oDisplay = new Object();
        oDisplay.lastContactedDate = lastContactedDate;
        oDisplay.lastContactedInfo = '';
        oDisplay.flagColor = '';
       
        console.log('lastContactedDate: ' + oDisplay.lastContactedDate);

        calculate_LastContactedInfo(oDisplay);
        $('#contactDetails_lastcontated').html(oDisplay.lastContactedInfo);

        calculate_LastContactedInfo(oDisplay);
        $('#contactDetails_lastcontated').html(oDisplay.lastContactedInfo);

    }

    /*********************************************************/
    /*populateDisplay_ContactInfoDetails*/
    /*********************************************************/
    function populateDisplay_ContactInfoDetails(oContactInfos)
    {
        console.log("entering: populateDisplay_ContactInfoDetails");
        console.log(oContactInfos);

        for (var i = 0; i < oContactInfos.length; i++) {
                
            var strActionImageLinks='';
            var oSingleContactInfo = oContactInfos[i];

            //avoid the URL (i.e. photo path/ content://) when we are populating the contact methods
            if (oSingleContactInfo.ContactInfoType.toLowerCase() == 'url') {
                continue;
            }


            switch (oSingleContactInfo.ContactInfoGroup) {
                case 'emails':
                    strActionImageLinks += buildIconLink('email', oSingleContactInfo.ContactInfo);
                    break;
                case 'photos':
                    //TODO: display phone here to allow user to change phone
                    //strActionImageLinks += buildIconLink('call', oSingleContactInfo.ContactInfo);
                    //strActionImageLinks += buildIconLink('text_message', oSingleContactInfo.ContactInfo);
                    break;
                case 'phoneNumbers':
                    strActionImageLinks += buildIconLink('call', oSingleContactInfo.ContactInfo);
                    strActionImageLinks += buildIconLink('text_message', oSingleContactInfo.ContactInfo);
                    //build the text link
                    //build the phone number link
                    break;
                default:
                    break;
            }

            console.log(strActionImageLinks);

            var itemToAdd = '<tr style="border-top: 1px solid #cdcdcd;">'
                                + '<td colspan="2" style="vertical-align: top">'
                                    + '<div class="tobewrap">'
                                    + '    <strong>' + oSingleContactInfo.ContactInfo + '</strong>'
                                    + '<span style="margin-top: -5px;display:  block;">'
                                    + '<i>' + oSingleContactInfo.ContactInfoType.toLowerCase() + '</i>'
                                    + '</span>'
                                    + '</div>'
                                + '</td>'
                                //+ '<td>'
                                //    + '<span>'
            	                //    + '     <i>' + oSingleContactInfo.ContactInfoType.toLowerCase() + '</i>'
                                //    + '</span>'
                                //+ '</td>'
                                + '<td class="tobewrap" style="display: inline-block;margin: 5px 10px 0 0;float: right;">'    //adjust here
                                + strActionImageLinks
                                + '</td>'
                            + '</tr>'

            $("#trContactInfos").append(itemToAdd);

            ////populate the list
            //var itemToAdd = '<li>'
            //                    + strActionImageLinks
            //                    + '<span class="contactName">'
            //	                    + '<strong>' + oSingleContactInfo.ContactInfo + '<span></span></strong>'
            //	                    + '<i>' + oSingleContactInfo.ContactInfoType.toUpperCase() + '</i>'
            //	                + '</span>'
            //                + '</li>';

            	                    //$("#contact_methods_list").append(itemToAdd);
        }
       


    }

    function callback_load_SingleContact_fromLocalStorage_Success(oSingleContact) {
        console.log("entering: callback_load_SingleContact_fromLocalStorage_Success");
        console.log(oSingleContact);

        //populate the contact section
        populateDisplay_ContactInfo(oSingleContact);

        //get the contact details and populate them
        dataService.get_SingleContact_Infos_FromLocalStorage(oSingleContact.Ukey,
                                                                populateDisplay_ContactInfoDetails,
                                                                errorHandler);
    };

    // onError: Failed to get the contacts
    //
    function callback_load_SingleContact_fromLocalStorage_Error(contactError) {
        console.log('entering: callback_load_SingleContact_fromLocalStorage_Error');
        console.log('error: ' + contactError);
        $("#contactsContainer").html("ERROR.unable to load contacts...");
    }
    

    /********************************************************************/
    //CALLBACKS: 
    /********************************************************************/
    function callback_ResetLastContacted_Success(newDateLastContacted) {
        console.log('entering: callback_ResetLastContacted_Success');

        //we'll update just that block
        populateDisplay_LastContacted(newDateLastContacted);
    }

    /********************************************************************/
    /* callback_ResetLastContacted_Error*/
    /********************************************************************/
    function callback_ResetLastContacted_Error(updateError) {
        console.log('entering: callback_ResetLastContacted_Error');
        console.log('error: ' + updateError);
        $("#contactsContainer").html("ERROR.unable to update error...");
    }

    return {

        //********************************************************************/
        //Init function
        //********************************************************************/
        fn_init: function () {

            //start the database
            dataService.startDatabase();

            console.log('entering: fn_init');

            //show message
            $("#loadingContainer").css("display", "inline");

            //get the single contact
            var arrQuerystring = getUrlVars()
            contactID = arrQuerystring["ref"];

            if (contactID && contactID > 0) {
                //load that variable
                this.fn_load_SingleContact_fromLocalStorage();

            }

            //hide message
            $("#loadingContainer").css("display", "none");

            //TODO: display an error container here
        },

        /***********************************************************************/
        /* GET SINGLE CONTACT FROM LOCAL STORAGE*/
        /***********************************************************************/
        fn_load_SingleContact_fromLocalStorage: function () {
            console.log('entering fn_load_SingleContact_fromLocalStorage for: ' + contactID);

            //get the single contact from our local table
            dataService.get_SingleContact_FromLocalStorage(contactID,
                                                           callback_load_SingleContact_fromLocalStorage_Success,
                                                           callback_load_SingleContact_fromLocalStorage_Error);

        },


        /***********************************************************************/
        /* RESET LAST CONTACTED                                               */
        /***********************************************************************/
        fn_ResetLastContacted: function (lastContactMethod) {
            console.log('entering: fn_UpdateLastContacted for: ' + contactID);


            //get the single contact
            var arrQuerystring = getUrlVars()
            contactID = arrQuerystring["ref"];

            if (contactID && contactID > 0) {
                //update that last contacted
                dataService.update_Table_UContacts_Reset_LastContacted( contactID,
                                                                        lastContactMethod,
                                                                        callback_ResetLastContacted_Success,
                                                                        callback_ResetLastContacted_Error);
            }

        },

        /***********************************************************************/
        /* REMINDERS - SAVE/UPDATE                                             */
        /***********************************************************************/
        fn_Reminders_SaveUpdate: function () {
            console.log('entering: fn_Reminders_SaveUpdate');

            var reminderPeriod = $("#contactDetails_ReminderPeriod").val();
            var reminderNum = $("#contactDetails_ReminderNum").val();

            //
            var oReminder = new Object();

            //moment().add('hours', 1).fromNow(); // "in an hour"
            var nextReminderDate = moment().add(reminderPeriod, reminderNum).format('MMMM Do YYYY, h:mm:ss a');

            alert(nextReminderDate);

            //get the values from the controls
            alert('reminderPeriod:' + reminderPeriod);
            alert('reminderNum:' + reminderNum);

        },

        /***********************************************************************/
        /* REFRESH TIMED AREAS                                               */
        /***********************************************************************/
        fn_Refresh_Timed_Areas: function(){
            //get the single contact
            var arrQuerystring = getUrlVars()
            contactID = arrQuerystring["ref"];

            if (contactID && contactID > 0) {
                //dataService.get_SingleContact_FromLocalStorage(contactID,
                //                                          callback_load_SingleContact_fromLocalStorage_Success,
                //                                          callback_load_SingleContact_fromLocalStorage_Error);
                //get the info from the db
            }
        },

        ////get all child categories of 'path' from database
        //getContacts: function (callback) {

        //    db.transaction(
        //        function (transaction) {
        //            transaction.executeSql(
        //                'SELECT * FROM contacts', [],
        //                function (transaction, result) {
        //                    var contacts = [], i, row;
        //                    for (i = 0; i < result.rows.length; i += 1) {
        //                        row = result.rows.item(i);
        //                        contacts.push(row);
        //                    }
        //                    callback(contacts);
        //                }, errorHandler);
        //        }
        //    );
        //},


        


        fn_ContactCategories_SaveUpdate: function () {
            console.log('entering: fn_ContactCategories_SaveUpdate');

            //get the single contact
            var arrQuerystring = getUrlVars()
            contactID = arrQuerystring["ref"];

            var oContactCategory = new Object();

            //collect the input
            oContactCategory.UKey_Contact = contactID;
            oContactCategory.contactCategory =  $("#contactDetails_CategoryType").val();

            dataService.save_SingleContactCategories(oContactCategory,
                                                           function successCB() {
                                                               //alert('yes sir');
                                                               $.jGrowl('Updated Successfully!', { theme: 'success' })
                                                           },
                                                           function errorCB() {
                                                               $.jGrowl('Update Failed!', { theme: 'failure' })
                                                           }
                                                      );


        }



    };
}());
